package cn.tq.pethome.emp.controller;

import cn.tq.pethome.bean.AjaxResult;
import cn.tq.pethome.bean.ResultBean;
import cn.tq.pethome.emp.domain.Employee;
import cn.tq.pethome.emp.query.EmployeeQuery;
import cn.tq.pethome.emp.service.IEmployeeService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/emp")
@Api(value = "员工的API",description="员工相关的CRUD功能")
public class EmployeeController {
    @Autowired
    private IEmployeeService employeeService;

    /**
     * 高級查詢
     * @param query
     * @return
     */
    @ApiOperation(value = "高级查询所有员工" )
    @PostMapping
    public ResultBean<Employee> queryEmployee(@RequestBody EmployeeQuery query){
        return employeeService.queryAll(query);
    }

    /**
     * 單個查詢
     * @param id
     * @return
     */
    @ApiOperation(value = "通过ID查询员工" )
    @GetMapping("/{id}")
    public Employee selectEmployee(@PathVariable("id")Long id){
        return employeeService.findById(id);
    }

    /**
     * 刪除數據
     * @param id
     * @return
     */
    @ApiOperation(value = "通过ID删除员工" )
    @DeleteMapping("/{id}")
    public AjaxResult delEmployee(@PathVariable("id")Long id){
        try {
            employeeService.delete(id);
            return AjaxResult.success();
        }catch (Exception e){
            e.printStackTrace();
            return AjaxResult.fail();
        }
    }

    /**
     * 添加或修改數據
     * @param emp
     * @return
     */
    @ApiOperation(value = "添加或修改员工" )
    @PutMapping
    public AjaxResult addOrUpEmployee(@RequestBody Employee emp){
        try {
            if (emp.getId()!=null){
                employeeService.update(emp);
            }else {
                employeeService.insert(emp);
            }
            return AjaxResult.success();
        }catch (Exception e){
            e.printStackTrace();
            return AjaxResult.fail();
        }
    }

    /**
     * 查询所有数据
     * @return
     */
    @GetMapping
    @ApiOperation(value = "查询所有数据" )
    public List<Employee> employees() {
        return employeeService.findAll();
    }

    /**
     * 批量删除
     * @param ids
     * @return
     */
    @PatchMapping
    @ApiOperation(value = "批量删除数据" )
    public AjaxResult batchDelete(@RequestBody List<Long> ids){
        try {
            employeeService.batchDelete(ids);
            return AjaxResult.success();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.fail();
        }
    }
}
